package com.xin.xinapiclientsdk.client;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import static com.xin.xinapiclientsdk.utils.SignUtils.genSign;


/**
 * API 调用
 */
public class XinApiClient {
    public static String GATEWAY_HOST = "http://49.233.186.145:8090";

    private String accessKey;

    private String secretKey;

    public XinApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public void setGatewayHost(String gatewayHost) {
        GATEWAY_HOST = gatewayHost;
    }


    private Map<String, String> getHeaderMap(String body, String method) throws UnsupportedEncodingException {
        HashMap<String, String> map = new HashMap<>();
        map.put("accessKey", accessKey);
        map.put("nonce", RandomUtil.randomNumbers(10));
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        map.put("sign", genSign(body, secretKey));
        body = URLUtil.encode(body, CharsetUtil.CHARSET_UTF_8);
        map.put("body", body);
        map.put("method", method);
        return map;
    }

    //调用接口
    public String invokeInterface(String params, String url, String method){
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpRequest.post(GATEWAY_HOST + url)
                    .header("Accept-Charset", CharsetUtil.UTF_8)
                    .addHeaders(getHeaderMap(params, method))
                    .body(params)
                    .execute();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return JSONUtil.formatJsonStr(httpResponse.body());
    }

    /**
     * 随机头像
     * sex 指定性别 sex=男
     * @return
     */
    public String randAvatar(String body){
       return invokeInterface(body,"/api/rand.avatar","GET");
    }

    /**
     * 随机图片
     * @return
     */
    public String randImages(String body){
        return invokeInterface(body,"/sjbz/api.php","GET");
    }

    /**
     * 心灵鸡汤
     */
    public String poisonChicken(String body){
        return invokeInterface(body,"/yan/api.php","GET");
    }

    /**
     * 短网址生成
     */
    public String long2dwz(String body){
        return invokeInterface(body,"/api/long2dwz","GET/POST");
    }

    /**
     * 网易云音乐热门评论随机API接口
     */
    public String hotComments(String body){
        return invokeInterface(body,"/api/comments.163","GET");
    }

    /**
     * 网易云音乐随机歌曲API接口
     */
    public String randMusic(String body){
        return invokeInterface(body,"/api/rand.music","GET");
    }


}
